import {  getUuid } from '@/utils/common'
import { categoryLibrary } from '@/api/turnover/ppw.js'

// 根据客户端返回的数据  造父子级关系
/**
 * 参数一:弹窗返回的数组对象 (必填)
 * 参数二:每个模块调用的标志==>用于识别不同模块的参数不一致 修改参数 (必填)
 * 参数三: billId (可选，有些模块新增的时候需要带如明细 没有billId)
 * 参数四: 入库（有且仅有一个模块使用 可不计入）
 */
function doChildren (list, sign, billId = '', businessType = null) {
    const mapObj = {}
    let arr = []
    list.forEach(e => {
        const children = []
        console.log(e.materialClassName, '111')
        e.materialClassNameArr = e.materialClassName.split('/')
        e.materialClassIdArr = e.materialClassId.split('/')
        // TODO: 统计小计
        let obj
        const topClassId =  e.materialClassIdArr
            .splice(0, 1)
            .toString()
        const topClassName = e.materialClassNameArr
            .splice(0, 1)
            .toString()
        if (!mapObj[topClassId]) {
            obj = {
                topClassId,
                topClassName,
                customId: topClassId,
                materialClassId: topClassId,
                materialClassName: topClassName,
                uuid: getUuid(),
                totalAmount: '',
                totalQuantity: '',
                type: businessType,
                businessType: businessType //入库下面的类型  可选
            }

            arr.push(obj)
            mapObj[topClassId] = obj
        } else {
            obj = mapObj[topClassId]
        }

        let addObj = {
            uuid: getUuid(),
            customId: getUuid(),
            amount: e.amount,
            billId,
            changeType: 1,
            oldState: 1,
            materialClassId: e.materialClassIdArr.join('/'), //物资类别id(
            materialClassName: e.materialClassNameArr.join('/'), //物资类别名称
            materialId: e.materialId, //物资id
            materialName: e.materialName, //物资名称
            unit: e.unit, //单位
            spec: e.spec || '', //规格
            texture: e.texture, //材质
        }

        if (sign === 'storage') { //如果业务类型有值  --  说明是物资在调用（入库）
            addObj.contractId = e.id
            addObj.receiptQuantity = e.notWarehosingQuantity //数量
            addObj.sourceDtlId = e.dtlId || e.billId //id

            addObj.timeUnit = e.timingUnit //计时单位
            addObj.timingUnitId = e.timingUnitId //计时单位Id
            addObj.leaseTime = e.leaseTime //租赁时间

            addObj.warehouseNameId = e.warehouseNameId //仓库id
            addObj.warehouseName = e.warehouseName //仓库
        } else if(sign === 'SalesReturn') { // 供方退货

            addObj.inventoryQuantity = e.quantity  //库存数量(选择库存)
            addObj.prevTotalReturnedQuantity = e.prevTotalReturnedQuantity  //上期退货数量(选择库存)
            addObj.inventoryId = e.dtlId  //截止本期末退货数量(选择库存)

        } else if (sign === 'procuremenPlan') { //年计划引入--采购计划
            addObj.annualDemandPlanDtlId = e.dtlId    //年计划id
            addObj.price = e.price    //单价
            addObj.quantity = e.surplusQuantity    //采购计划--剩余数量
        } else if (sign === 'procuremenPlanChenge') { //年计划引入--采购计划变更
            addObj.annualDemandPlanDtlId = e.dtlId    //年计划id
            addObj.priceChanged = e.price    //单价
            addObj.quantityChanged = e.surplusQuantity    //采购计划--剩余数
        }
        else if (sign === 'momentNeedPlan') { //年计划引入--临时需用计划
            addObj.annualDemandPlanDtlId = e.dtlId    //年计划id
            addObj.price = e.price    //单价
            addObj.quantity = e.surplusQuantity    //数量
        }
        else if (sign === 'momentNeedPlanChenge') { //年计划引入--临时需用计划
            addObj.annualDemandPlanDtlId = e.dtlId    //年计划id
            addObj.priceChanged = e.price    //单价
            addObj.quantityChanged = e.surplusQuantity    //数量
        }
        else if (sign === 'leasePlan') { //年计划引入--租赁计划
            addObj.annualDemandPlanDtlId = e.dtlId    //年计划id
            addObj.price = e.price    //单价
            addObj.quantity = e.surplusQuantity    //数量
        }
        else if (sign === 'leasePlanChenge') { //年计划引入--租赁计划变更
            addObj.annualDemandPlanDtlId = e.dtlId    //年计划id
            addObj.priceChanged = e.price    //单价
            addObj.quantityChanged = e.surplusQuantity    //数量
        }
        else if (sign === 'base') { //年计划从基础库基础库引入
            addObj.materialId = e.billId
            addObj.texture = null
            addObj.demandQuantity = 0
            addObj.deployableQuantity = 0
            addObj.leaseQuantity = 0
            addObj.purchaseQuantity = 0
            addObj.purchasePrice = 0
            addObj.timeUnit = null
            addObj.estimatedTime = 0
            addObj.leasePrice = 0
            addObj.amount = 0 //金额
            addObj.warehouseNameId = e.warehouseNameId //仓库id
            addObj.warehouseName = e.warehouseName //仓库

        } else if (sign === 'baseYearChange') {
            addObj.leaseQuantityChanged  = 0
            addObj.leasePriceChanged  = 0
            addObj.estimatedTimeChanged  = 0
            addObj.purchaseQuantityChanged  = 0
            addObj.purchasePriceChanged = 0
            addObj.amountChanged = 0
            addObj.demandQuantityChanged = 0
            addObj.deployableQuantityChanged = 0

        }

        else if (sign === 'receive') { //周才领料
            addObj.inventoryQuantity = e.quantity
            addObj.sourceDtlId = e.dtlId //id
            addObj.inventoryId = e.dtlId //id
            addObj.prevTotalReturnedQuantity = e.returnQuantity //截至上期末
            addObj.supplierName = e.supplierName //供应商
            addObj.supplierId = e.supplierId //供应商Id

            addObj.warehouseName = null
            addObj.timeUnit = null
            addObj.usageTime = null
            addObj.receivedQuantity = null
            addObj.warehouseName = e.warehouseName //仓库
            addObj.warehouseId = e.warehouseId
            addObj.source = e.source //来演

        } else if (sign === 'inventorySurplusLosses') {//盘盈盘亏
            addObj.bookQuantity = e.quantity
            addObj.inventoryQuantity = 0 //实盘数
        }
        else if (sign === 'Outstock') { //周才领料

            addObj.sourceDtlId = e.dtlId
            addObj.receiveWarehouseName = e.warehouseName
            addObj.receiveWarehouseId = e.warehouseId
            addObj.receiveQuantity = e.receiveQuantity
            addObj.currReturnQuantity = e.canReturnQuantity //可退库数量

            addObj.prevTotalReturnQuantity = e.prevTotalReturnQuantity  //	截至上期末退库数量
            addObj.inventoryQuantity = e.quantity  //	库存数量
            // addObj.currReturnQuantity = e.canReturnQuantity - e.prevTotalReturnQuantity //领料数量-截止上期末

        } else if (sign === 'revolveAllocation') {
            addObj.price = e.price

        } else if (sign === 'leisureCheck') {
            addObj.idleQuantity = e.quantity
            addObj.source = e.source
            addObj.sourceDtlId = e.dtlId
            // 调拨
            addObj.allocationQuantity = e.quantity
            addObj.money = e.money
            addObj.price = e.price

        } else if (sign === 'Idle') {//内阻调动选明细
            addObj.sourceDtlId = e.dtlId
            addObj.quantity = e.quantity

        } else if (sign === 'LeaseOut') {//租赁退场
            addObj.sourceDtlId = e.dtlId
            addObj.warehousingQuantity = e.receiptQuantity //入库数量
            addObj.storehouseName = e.warehouseName //仓库
            addObj.storehouseId = e.warehouseId //仓库id
            addObj.currReturnQuantity = e.notReturnQuantity //本次退场数量
            addObj.prevTotalReturnQuantity = e.prevTotalReturnQuantity //截止上期末
            addObj.compensateQuantity = e.compensateQuantity //赔偿数量
            addObj.lossReason = '' //损耗原因

        }else if (sign === 'Inventory') {//摊销盘点
            addObj.bookQuantity = e.bookQuantity //账面数量
            addObj.sourceDtlId = e.dtlId

            addObj.subItem = e.subItem //分部分项
            addObj.type = e.type //发料类型
            addObj.warehouseId = e.warehouseId //仓库id
            addObj.warehouseName = e.warehouseName //仓库名称

        } else if (sign === 'amortizationMoney') { //金额摊销
            addObj.sourceDtlId = e.dtlId

            addObj.prevTotalAmortizationAmount = e.prevTotalAmortAmount//截至上期末已摊销金额
            // addObj.prevTotalAmortizationQuantity = e.prevTotalAmortQuantity//截至上期末已摊销数量
            addObj.currTotalAmortizationQuantity = null//本期末
            addObj.currAmortizationAmount = e.surplusAmortizationAmount //本次摊销金
            addObj.amount = e.acceptAmount//原金额
            addObj.amortizationType = e.amortizationType//按照金额 用于判断表格内逻辑
            addObj.currTotalAmortizationAmount = e.currTotalAmortAmount//截至本期末已摊销金额

        } else if (sign === 'amortizationQuanty') {
            addObj.sourceDtlId = e.dtlId

            addObj.quantity = e.inventoryQuantity//原数量
            addObj.currAmortizationQuantity = e.consumeQuantity//本次报销数量
            addObj.prevTotalAmortizationQuantity = e.prevTotalAmortQuantity//截止上期末已摊销数量
            addObj.amortizationType = e.amortizationType//按照数量 用于判断表格内逻辑

        } else if (sign === 'amortizationChange') { //摊销比例变更
            addObj.sourceDtlId = e.dtlId
            addObj.checkQuantity = e.acceptanceQuantity //验收数量
            addObj.checkMoney = e.acceptanceAmount //验收金额
            addObj.totalAmortizationRatio = e.totalAmortizationRatio //摊销总比例
            addObj.amortizationDate = e.amortizationDate //摊销总比例

        } else if (sign === 'settl') {
            addObj.sourceDtlId = e.dtlId
            addObj.settlQuantity = e.settlQuantity
        }
        // 物资名称
        children.push( addObj )
        obj.children = !obj.children
            ? children
            : obj.children.concat(children)
        const count = obj.children.reduce(
            (prev, c) => (prev += c.amount || 0),
            0
        )

        obj.materialName = `小计： ${count}`
        obj.children = uniqueArray(obj.children, 'customId')
    })

    return arr

}
function uniqueArray (arr, key) {
    const map = new Map()
    return arr.filter(item => {
        const val = item[key] + '' || getUuid()
        return !map.has(val) && map.set(val, 1)
    })
}
// 基础库明细数组追加
function baseDetailListAdd (id, type) {
    return new Promise(resolve => {

        categoryLibrary().then(data => {
            if (data) {
                const obj = doChildren(data, 'base', id, type)
                resolve(obj[0].children)
            }
        })

    })

}

export {
    doChildren,
    baseDetailListAdd
}